package com.xtedu.examproject.filter;

import com.xtedu.examproject.entity.User;
import com.xtedu.examproject.util.RedisUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class LoginFilter implements Filter {
    private List<String> excludedUrls;//可以直接放行
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        //拿到不需要登录状态严重的请求路径 login css assets ....
        ///login,/css,/captcha,/js,/assets,/fonts,/images
        String excludedUrlsString=filterConfig.getInitParameter("excludedUrls");
        //["/login","/css","/captcha",,,,"/images"]
        excludedUrls=Arrays.asList(excludedUrlsString.split(","));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String pathInfo=request.getServletPath();// /login
        //excludedUrls.stream().anyMatch(excludedUrl -> pathInfo.startsWith(excludedUrl)) pathInfo这个路径是否在excludeUrls中出现过
        // /login/add   /login/add.startsWith("/login")得到true
        if(excludedUrls.stream().anyMatch(pathInfo::startsWith)){
            filterChain.doFilter(servletRequest, servletResponse);//我处理完了之后继续执行吧
            return;
        }
        //必须要处于登录状态
        HttpSession session =request.getSession();
        User currentLogin= RedisUtil.getObject("session:"+session.getId(), User.class);
        if(currentLogin==null){//没登陆
            response.sendRedirect("login");
        }else{
            servletRequest.setAttribute("user",currentLogin);
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
